/**
 * Copyright (c) Software Institute of PKU
 * All rights reserved. 
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */
package edu.pku.sei.modeler.actions;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.modeler.model.core.MetaModel;
import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.model.structure.MetaLink;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.modeler.model.structure.StructurePackage;
import edu.pku.sei.modeler.project.ProjectRegistry;

/**
 * @author danny
 *
 */
public class OpenElementAction extends Action {
	IWorkbenchPage workbenchPage;
	private Object obj;
	public OpenElementAction(){
		super();
		this.setText("open");
		setToolTipText("open this element");
		this.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
	}
	public void setTreeObj(Object obj) {
		this.obj = obj;
	}
	public void run(){
		if(obj instanceof MetaModelElement) {
			MetaModel model = ((MetaModelElement)obj).getModel();
//			ProjectRegistry.getDefault().openDiagram(obj, model);
			List diagrams = model.getInstancesForType(StructurePackage.__DIAGRAM__);
			List<MetaDiagram> result = new ArrayList<MetaDiagram>();
			for(int i=0; i<diagrams.size(); i++) {
				MetaDiagram diag = (MetaDiagram)diagrams.get(i);
				List<MetaNode> nodes = diag.getNodes();
				List<MetaLink> links = new ArrayList<MetaLink>();
				for(MetaNode node:nodes) {
					if(node.getModelElement() == obj) {
						result.add(diag);
						break;
					}
					links.addAll(node.getOutgoings());
				}
				for(MetaLink link:links) {
					if(link.getModelElement() == obj) {
						result.add(diag);
						break;
					}
				}
			}
			for(int i=0; i<result.size(); i++) {
				System.out.println(result.get(i));
			}
			OpenMultiDiagramDialog dlg = new OpenMultiDiagramDialog(workbenchPage.getActivePart().getSite().getShell());
			dlg.setDiagrams(result);
			if(dlg.open() == SWT.OK) {
				result = dlg.getResult();
				for(MetaDiagram diag:result) {
					ProjectRegistry.getDefault().openDiagram(diag, model);
				}
			}
		}
	}
	public IWorkbenchPage getWorkbenchPage() {
		return workbenchPage;
	}
	public void setWorkbenchPage(IWorkbenchPage workbenchPage) {
		this.workbenchPage = workbenchPage;
	}
}
